<template>
  <div class="customer-management">
    <div class="search-box">
      <el-row :gutter="6">
        <el-col :span="8">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入客户名称、电话、电子邮箱搜索"
            @keyup.enter="handleSearch"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button color="#19af7d" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </div>

    <el-button color="#19af7d" @click="addForm" style="margin-bottom: 20px"
      >新增客户</el-button
    >

    <el-table :data="dataList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="客户名称" align="center" />
      <el-table-column prop="phone" label="联系电话" align="center" />
      <el-table-column prop="idCard" label="身份证" align="center" />
      <el-table-column prop="email" label="电子邮箱" align="center" />
      <el-table-column prop="sex" label="性别" align="center" />
      <el-table-column
        v-if="type === 'overdue'"
        prop="overdueDays"
        label="逾期天数"
        align="center"
      />

      <el-table-column
        v-if="type === 'all'"
        prop="customerType"
        label="客户类型"
        width="150"
        align="center"
      >
        <template #default="scope">
          <el-tag :type="getCustomerTagType(scope.row.customerType)">
            {{ getCustomerTypeName(scope.row.customerType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="editForm(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <Pagination v-model="currentPage" :page-size="pageSize" :total="total" />

    <Form
      v-model="dialogVisible"
      :isEdit="isEdit"
      :customerFormData="customerForm"
      @save="handleSave"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/Pagination.vue";
import Form from "./form.vue";

// 获取路由实例
const route = useRoute();
// 初始化 type，默认为 all，从路由获取值
const type = ref(route.query.type || "all");
console.log(type.value);

// 所有客户数据
const allData = ref([
  {
    id: 1,
    name: "张三",
    idCard: "11010119900101001X",
    phone: "13800138000",
    email: "zhangsan@qq.com",
    sex: "男",
    createTime: "2023-01-01",
    customerType: "normal",
  },
  {
    id: 2,
    name: "李四",
    idCard: "11010119900101001X",
    phone: "13900139000",
    email: "lisi@qq.com",
    sex: "女",
    createTime: "2023-01-02",
    customerType: "overdue",
    overdueDays: 10,
  },
]);
// 搜索
const searchKeyword = ref("");
// 当前页码
const currentPage = ref(1);
// 分页数量
const pageSize = ref(10);

// 根据搜索过滤客户数据
const filteredData = computed(() => {
  if (!searchKeyword.value) return allData.value;
  const keyword = searchKeyword.value.toLowerCase();
  return allData.value.filter(
    (item) =>
      item.name.toLowerCase().includes(keyword) ||
      item.idCard.toLowerCase().includes(keyword) ||
      item.phone.toLowerCase().includes(keyword) ||
      item.email.toLowerCase().includes(keyword) ||
      item.sex.toLowerCase().includes(keyword)
  );
});

// 根据当前页码和每页显示数量，计算当前页要显示的客户数据
const dataList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 计算过滤后总条数
const total = computed(() => filteredData.value.length);

const dialogVisible = ref(false);
const isEdit = ref(false);
// 客户表单数据
const customerForm = ref({
  id: null,
  name: "",
  idCard: "",
  phone: "",
  email: "",
  sex: "",
});

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
};

const addForm = () => {
  isEdit.value = false;
  customerForm.value = {
    id: null,
    name: "",
    idCard: "",
    phone: "",
    email: "",
    sex: "",
  };
  dialogVisible.value = true;
};

const editForm = (row) => {
  isEdit.value = true;
  customerForm.value = { ...row };
  dialogVisible.value = true;
};

const generateId = () => {
  return Math.max(...allData.value.map((item) => item.id), 0) + 1;
};

const handleSave = (data) => {
  dialogVisible.value = false;
  if (isEdit.value) {
    const index = allData.value.findIndex((item) => item.id === data.id);
    if (index !== -1) {
      // 使用浅拷贝更新数据，保证响应式
      allData.value = [
        ...allData.value.slice(0, index),
        data,
        ...allData.value.slice(index + 1),
      ];
    }
  } else {
    const newCustomer = {
      ...data,
      id: generateId(),
      createTime: formatDate(new Date()),
    };
    // 使用浅拷贝添加新数据
    allData.value = [...allData.value, newCustomer];
  }
  currentPage.value = 1;
};

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month}-${day}`;
};

// 获取客户类型标签类型
const getCustomerTagType = (type) => {
  switch (type) {
    case "normal":
      return "success";
    case "overdue":
      return "danger";
    default:
      return "info";
  }
};

// 获取客户类型名称
const getCustomerTypeName = (type) => {
  switch (type) {
    case "normal":
      return "普通客户";
    case "overdue":
      return "逾期客户";
    default:
      return "不良客户";
  }
};

// 删除客户
const handleDelete = (id) => {
  ElMessageBox.confirm("确定要删除该客户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allData.value = allData.value.filter((item) => item.id !== id);
      ElMessage.success("删除客户成功");
      if (dataList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>

<style scoped lang="scss">
@use "./index.scss";
</style>
